package gov.kqqzyyy.monkey.radiologyscreen.ui;

import android.app.Activity;
import android.app.FragmentManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.widget.Toast;

import java.lang.ref.WeakReference;

import gov.kqqzyyy.monkey.radiologyscreen.R;
import gov.kqqzyyy.monkey.radiologyscreen.mytools.ProgressDialogFragment;
import gov.kqqzyyy.monkey.radiologyscreen.mytools.UpdateInfo;

/**
 * Created by Monkey on 2017/11/25.
 * 设置类
 */

public class FragmentPreferences extends Activity {

    private ProgressDialogFragment progressDialogFragment;
    private PrefsFragement prefsFragement;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        prefsFragement = new PrefsFragement();
        FragmentManager fragmentManager = getFragmentManager();
        if (fragmentManager != null) {
            fragmentManager.beginTransaction().replace(android.R.id.content, prefsFragement).commit();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (prefsFragement != null && prefsFragement.serverTestThread != null && prefsFragement.serverTestThread.isAlive()) {
            prefsFragement.serverTestThread.interrupt();
            prefsFragement.serverTestThread = null;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(getApplicationContext(), SplashActivity.class);
            startActivity(intent);
        }
        return super.onKeyDown(keyCode, event);
    }

    // 设置类
    public static class PrefsFragement extends PreferenceFragment implements Preference.OnPreferenceChangeListener {

        SharedPreferences mSharedPreferences;
        EditTextPreference mServerAddPreference; //服务器地址
        String preServerAdd;

        MyHandler myHandler;
        Thread serverTestThread;

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            mSharedPreferences = getPreferenceManager().getSharedPreferences();
            myHandler = new MyHandler((FragmentPreferences) getActivity());
            addPreferencesFromResource(R.xml.preferences);//从XML文件加载选项
            onBindXML();

            setAddressText();
            mServerAddPreference.setOnPreferenceChangeListener(this);


        }

        private void setAddressText() {
            preServerAdd = mSharedPreferences.getString("server_address", getString(R.string.default_server));
            mServerAddPreference.setText(preServerAdd);
            mServerAddPreference.setSummary(preServerAdd);
        }

        private void onBindXML() {
            mServerAddPreference = (EditTextPreference) findPreference("server_address");
        }

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if (preference instanceof ListPreference) {
                ListPreference listPreference = (ListPreference) preference;
                CharSequence[] entries = listPreference.getEntries();
                int index = listPreference.findIndexOfValue((String) newValue);
                listPreference.setSummary(entries[index]);
            } else {
                ((FragmentPreferences) getActivity()).showProgressDialog();
                final String newAdd = newValue.toString();
                serverTestThread = new Thread(() -> {
                    Message message = new Message();
                    if (UpdateInfo.isServerAvailable(newAdd)) {
                        message.what = 0x11;
                    } else {
                        message.what = 0x12;
                        mSharedPreferences.edit().putString("server_address", preServerAdd).apply();
                    }
                    myHandler.sendMessage(message);
                    serverTestThread.interrupt();
                    serverTestThread = null;
                });
                serverTestThread.start();
            }
            return true;
        }

    }

    private static class MyHandler extends Handler {
        WeakReference<FragmentPreferences> mActivity;

        MyHandler(FragmentPreferences activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            FragmentPreferences activity = mActivity.get();
            activity.cancelProgressDialog();
            switch (msg.what) {
                case 0x11:
                    Toast.makeText(activity, "服务器连接成功,重启该界面", Toast.LENGTH_SHORT).show();
                    activity.doRestart();
                    break;
                case 0x12:
                    Toast.makeText(activity, "服务器连接失败，重置默认地址", Toast.LENGTH_SHORT).show();
                    break;
            }
            activity.prefsFragement.setAddressText();
        }
    }

    private void doRestart() {
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

    private void cancelProgressDialog() {
        if (progressDialogFragment != null && progressDialogFragment.getDialog() != null) {
            progressDialogFragment.getDialog().dismiss();
        }
    }

    private void showProgressDialog() {
        cancelProgressDialog();
        progressDialogFragment = new ProgressDialogFragment();
        progressDialogFragment.setMessage("服务器连接测试中");
        progressDialogFragment.show(getFragmentManager(), "downLoading");
    }

}
